package com.tth.learn.addproperties.java1;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;

/**
 * @Author tth
 * @Date 2022/12/28 16:45
 */
public class URLTest {
    @Test
    public void test1() throws MalformedURLException {
        URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=tth&password=123456");
        // 获取URL的协议名
        System.out.println(url.getProtocol()); // http
        // 获取URL的主机名
        System.out.println(url.getHost()); // localhost
        // 获取URL的端口号
        System.out.println(url.getPort()); // 8080
        // 获取URL的文件路径
        System.out.println(url.getPath()); // /examples/beauty.jpg
        // 获取URL的文件名
        System.out.println(url.getFile()); // /examples/beauty.jpg?username=tth&password=123456
        // 获取URL的参数
        System.out.println(url.getQuery()); // username=tth&password=123456
    }

    @Test
    public void test2() {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/lbxx.jpg?username=tth&password=123456");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("lbxx.jpg");

            byte[] buff = new byte[1024];
            int len;
            while ((len = is.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }

            System.out.println("图片保存成功！");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != urlConnection) {
                urlConnection.disconnect();
            }
        }
    }
}
